
const { videoModel, commentModel, likeModel, subscribeModel } = require('../models/index')
const {setHotc,getTopHots} = require('../models/redis/redisHotVideo')
// 观看+1 点赞+2 评论+2  收藏+3 
/**
 * 
 * @param {*} req 
 * @param {*} res 
 * @description 新建视频操作
 */
const createvideo = async (req, res) => {
    let obj = req.body
    obj.users = req.userinfo['_id']
    const videomodle = new videoModel(obj)
    try {
        const dbback1 = await videomodle.save()
        const dbback = await videoModel.findById(dbback1._id).populate('users');
        if (dbback) {
            res.status(200).json({
                error: 0,
                msg: '视频创建成功',
                data: dbback
            })
        } else {
            res.status(400).json({
                error: 1,
                msg: '视频创建失败',
            })
        }
    } catch (err) {
        res.status(400).json({
            error: 1,
            msg: '视频创建失败',
        })
    }
}

/**
 * 视频列表分页
 */
const videolist = async (req, res) => {
    const { pagesize = 5, page = 1 } = req.query
    try {
        const skip = (page - 1) * pagesize;
        const totalCount = await videoModel.countDocuments();
        const videlist = await videoModel
            .find()
            .skip(skip)
            .limit(pagesize)
            .sort({ updatedAt: -1 })
            .populate('users', '_id name headimage')
        res.status(200).json({
            error: 0,
            msg: '获取成功',
            data: videlist,
            totalCount
        })

    } catch (err) {
        res.status(400).json({
            error: 1,
            msg: err,
        })
    }
}

/**
 * 获取视频详情
 */
const video = async (req, res) => {
    const { videoid } = req.params

    try {
        let dbback = await videoModel.findById(videoid).populate('users', 'name _id headimage')
        dbback = dbback.toJSON()
        dbback.islike = false
        dbback.isDislike = false
        dbback.isSubscribe = false
        if(req.userinfo){
            if(await likeModel.findOne({video:videoid,user:req.userinfo._id,like:1})){
                dbback.islike = true
            }
            if(await likeModel.findOne({video:videoid,user:req.userinfo._id,like:-1})){
                dbback.isDislike = true
            }
            if(await subscribeModel.find({user:req.userinfo._id,channel:dbback.users._id})){
                dbback.isSubscribe = true
            }
        }
        await setHotc(videoid,1)
        res.status(200).json({
            error: 0,
            msg: '获取成功',
            data: dbback,
        })
    } catch (err) {
        console.log(err)
        res.status(400).json({
            error: 1,
            msg: err,
        })
    }
}
/**
 * 添加视频评论
 */

const addcomment = async (req, res) => {
    const video_id = req.params.videoid
    const { comment = '' } = req.body
    if (comment === '') {
        return res.status(400).json({
            error: 1,
            msg: '评论不可以为空'
        })
    }
    const videoInfo = await videoModel.findOne({ _id: video_id })
    if (!videoInfo) {
        return res.status(400).json({
            error: 1,
            msg: '该视频不存在'
        })
    }
    try {
        const comments = new commentModel({
            video: video_id,
            user: req.userinfo._id,
            comments: comment
        })
        await comments.save()
        videoInfo.commnetcount++
        await videoInfo.save()
        await setHotc(video_id,2)
        res.status(200).json({
            error: 0,
            msg: '评论成功',
        })
    } catch (err) {
        console.log(err)
        res.status(400).json({
            error: 1,
            msg: err,
        })
    }
}

//获取评论列表
const commentlist = async (req, res) => {
    const { pagesize = 10, page = 1 } = req.query
    const videoid = req.params.videoid
    try {
        const skip = (page - 1) * pagesize
        const dbback = await commentModel
            .find({ video: videoid })
            .skip(skip)
            .limit(pagesize)
            .populate('user', '_id name image ')
        const commentcount = await commentModel.countDocuments({ video: videoid })
        res.status(200).json({
            error: 0,
            msg: '评论列表获取成功',
            data: dbback,
            count: commentcount
        })


    } catch (err) {
        console.log(err)
        res.status(400).json({
            error: 1,
            msg: err,
        })
    }
}

//删除评论
const deletecomment = async (req, res) => {
    const user_id = req.userinfo._id
    const comment_id = req.params.commentid
    const video_id = req.params.videoid
    try {
        const videoinfo = await videoModel.findOne({ _id: video_id })
        if (!videoinfo) {
            return res.status(400).json({
                error: 1,
                msg: '视频已经不存在',
            })
        }
        const commentinfo = await commentModel.findById(comment_id)
        if (!commentinfo) {
            return res.status(400).json({
                error: 1,
                msg: '评论已经不存在',
            })
        }
        if (!commentinfo.user.equals(user_id)) {
            return res.status(400).json({
                error: 1,
                msg: '该评论不是自己的不能删除',
            })
        }
        await commentinfo.deleteOne({ _id: comment_id })
        videoinfo.commnetcount--
        await videoinfo.save()
        res.status(200).json({
            error: 1,
            msg: '删除成功'
        })

    } catch (err) {
        console.log(err)
        res.status(400).json({
            error: 1,
            msg: err,
        })
    }


}
//设置视频的喜欢
const like = async (req, res) => {
    const user_id = req.userinfo._id
    const video_id = req.params.videoid
    let islike = true
    try {
        const videoinfo = await videoModel.findById(video_id)
        if (!videoinfo) {
            return res.status(400).json({
                error: 1,
                msg: '该视频已经不存在'
            })
        }
        const likeinfo = await likeModel.findOne({
            user: user_id,
            video: video_id
        })
        //表示之前已经点击过喜欢了  就把这个数据清空
        if (likeinfo && likeinfo.like === 1) {
            await likeinfo.deleteOne(
                {
                    user: user_id,
                    video: video_id
                }
            )
            islike = false
        } else if (likeinfo && likeinfo.like === -1) {
            likeinfo.like = 1
            await setHotc(videoid,3)
            await likeinfo.save()
        } else {
            await new likeModel({
                user: user_id,
                video: video_id,
                like: 1
            }).save()
            await setHotc(videoid,3)
        }

        videoinfo.likecount = await likeModel.countDocuments({
            like: 1,
            video: video_id
        })

        videoinfo.dislikecount = await likeModel.countDocuments({
            like: -1,
            video: video_id
        })

        await videoinfo.save()
        res.status(200).json({
            error: 1,
            msg: islike ? '已设置为喜欢' : '取消喜欢',
            islike
        })

    } catch (err) {
        console.log(err)
        res.status(400).json({
            error: 1,
            msg: err
        })
    }
}

//设置视频的不喜欢
const dislike = async (req, res) => {
    const user_id = req.userinfo._id
    const video_id = req.params.videoid
    let isdislike = true
    try {
        const videoinfo = await videoModel.findById(video_id)
        if (!videoinfo) {
            return res.status(400).json({
                error: 1,
                msg: '该视频已经不存在'
            })
        }
        const likeinfo = await likeModel.findOne({
            user: user_id,
            video: video_id
        })
        //表示之前已经点击过喜欢了  就把这个数据清空
        if (likeinfo && likeinfo.like === -1) {
            await likeinfo.deleteOne(
                {
                    user: user_id,
                    video: video_id
                }
            )
            isdislike = false
        } else if (likeinfo && likeinfo.like === 1) {
            likeinfo.like = -1
            await likeinfo.save()
        } else {
            await new likeModel({
                user: user_id,
                video: video_id,
                like: -1
            }).save()
        }

        videoinfo.likecount = await likeModel.countDocuments({
            like: 1,
            video: video_id
        })

        videoinfo.dislikecount = await likeModel.countDocuments({
            like: -1,
            video: video_id
        })

        await videoinfo.save()
        res.status(200).json({
            error: 1,
            msg: isdislike ? '已设置为不喜欢' : '取消不喜欢',
            isdislike
        })

    } catch (err) {
        console.log(err)
        res.status(400).json({
            error: 1,
            msg: err
        })
    }
}

//喜欢视频列表
const likelist = async (req, res) => {
    const { pagesize = 10, page = 1 } = req.query
    const user_id = req.userinfo._id
    const skip = (page - 1) * pagesize
    try {
        const likeinfo = await likeModel.find({ user: user_id, like: 1 })
            .skip(skip).limit(pagesize).populate('video', '_id title vodid user').populate('user', '_id name image ')
        const likecount = await likeModel.countDocuments({ user: user_id, like: 1 })
        res.status(200).json({
            error: 0,
            msg: '成功获取喜欢列表',
            data: likeinfo,
            count: likecount
        })

    } catch (err) {
        console.log(err)
        res.status(400).json({
            error: 1,
            msg: err
        })
    }
}


//获取热门视频
const tophots = async (req,res)=>{
    const {size= 5} = req.params
    const tophots = await getTopHots(size)
    console.log('tophots',tophots)
    res.end()
}

module.exports = {
    createvideo,
    videolist,
    video,
    addcomment,
    commentlist,
    deletecomment,
    like,
    dislike,
    likelist,
    tophots
}